package com.boby.homecamera.util

import io.jsonwebtoken.*
import io.jsonwebtoken.security.Keys
import java.util.*
import javax.crypto.SecretKey

object JwtUtil {
    // 建议使用更复杂的密钥
    private var SECRET = "my-super-secret-key-that-is-very-safe-123456"
    private var KEY: SecretKey = Keys.hmacShaKeyFor(SECRET.toByteArray())

    private var ACCESS_TOKEN_EXPIRATION = 5 * 60 * 1000L     // 5分钟
    private const val REFRESH_TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000L // 7天

    fun setTokenExpiration(day:Int){
        ACCESS_TOKEN_EXPIRATION = day * 24 * 60 * 60 * 1000L
    }
    fun updateKey(){
        SECRET = UUID.randomUUID().toString()
        KEY = Keys.hmacShaKeyFor(SECRET.toByteArray())
    }
    // 创建 token
    fun generateToken(username: String): String {
        val now = Date()
        val expiryDate = Date(now.time + ACCESS_TOKEN_EXPIRATION)

        return Jwts.builder()
            .setSubject(username)
            .setIssuedAt(now)
            .setExpiration(expiryDate)
            .signWith(KEY, SignatureAlgorithm.HS256)
            .compact()
    }

    fun createAccessToken(userId: String): String {
        val now = Date()
        val expiryDate = Date(now.time + ACCESS_TOKEN_EXPIRATION)
        return Jwts.builder()
            .setSubject(userId)
            .setIssuedAt(now)
            .setExpiration(expiryDate)
            .signWith(KEY, SignatureAlgorithm.HS256)
            .compact()
    }

    // 校验 token 并提取用户名
    fun validateToken(token: String?): String? {
        return try {
            val claims = Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
            claims.body.subject // 返回用户名
        } catch (e: Exception) {
            null
        }
    }


    fun createRefreshToken(userId: String): String {
        val now = Date()
        return Jwts.builder()
            .setSubject(userId)
            .setIssuedAt(now)
            .setExpiration(Date(now.time + REFRESH_TOKEN_EXPIRATION))
            .signWith(KEY,SignatureAlgorithm.HS256)
            .compact()
    }


    fun getUserId(token: String): String? {
        return try {
            val claims = Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
            claims.body.subject // 返回用户名
        } catch (e: Exception) {
            null
        }
    }

}
